package com.chenss.dragonser.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.util.ArrayMap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.chenss.dragonser.R;
import com.chenss.dragonser.activity.GoodsDetailsActivity;
import com.chenss.dragonser.activity.MainActivity;
import com.chenss.dragonser.activity.QrPicActivity;
import com.chenss.dragonser.adapter.GoodsListAdapter;
import com.chenss.dragonser.app.AppInfo;
import com.chenss.dragonser.app.Constant;
import com.chenss.dragonser.base.BaseFragment;
import com.chenss.dragonser.model.GoodsListModel;
import com.chenss.dragonser.network.NetworkRequest;
import com.chenss.dragonser.network.RequestCallbcak;
import com.chenss.dragonser.response.GoodsListResponse;
import com.chenss.dragonser.utils.GsonUtil;
import com.chenss.dragonser.utils.ToastUtil;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.jwenfeng.library.pulltorefresh.PullToRefreshLayout;

import org.json.JSONException;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * PageName:
 * Create by chenss at 2018/4/21 14:27
 */
public class GoodsFragment extends BaseFragment implements RequestCallbcak, BaseRefreshListener {
    TextView tv_page_title;
    TextView tv_right;
    private TextView tv_tab_left;
    private TextView tv_tab_right;

    ListView mListView;
    List<GoodsListModel> list = new ArrayList<>();
    GoodsListAdapter listAdapter;
    String type = "1";//1.库存， 2.销量
    public NetworkRequest networkRequest;//网络请求
    public ArrayMap<String, String> parmMap;//请求参数封装
    PullToRefreshLayout pullToRefreshLayout;

    private int pageNo = 1;//当前页数
    private int totalpage = 0;//总条数
    private final static int REFRESHING = 0x010;
    private final static int LOADMORE = 0x020;
    int freshState = REFRESHING;//默认是刷新
    boolean isEntered = false;

    @Override
    public int bindLayout() {
        return R.layout.frag_tab_goods;
    }

    @Override
    public void initView(View view) {
        tv_page_title = findView(view, R.id.tv_page_title);
        tv_right = findView(view, R.id.tv_right);
        tv_page_title.setText("产品管理");
        tv_right.setVisibility(View.VISIBLE);
        tv_right.setOnClickListener(this);
        tv_right.setText("收钱");
        tv_tab_left = findView(view, R.id.tv_tab_left);
        tv_tab_right = findView(view, R.id.tv_tab_right);
        tv_tab_left.setOnClickListener(this);
        tv_tab_right.setOnClickListener(this);
        tv_tab_left.setText("库存管理");
        tv_tab_right.setText("销售管理");


        pullToRefreshLayout = findView(view, R.id.pullToRefreshLayout);
        pullToRefreshLayout.setRefreshListener(this);
        mListView = findView(view, R.id.mListView);
        listAdapter = new GoodsListAdapter(getActivity(), list, type);
        mListView.setAdapter(listAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(type.equals("1")){
                    Intent intent = new Intent(getActivity() , GoodsDetailsActivity.class);
                    intent.putExtra("goods_id" , list.get(position).getSh_goods_id());
                    startActivity(intent);
                }
            }
        });


    }

    @Override
    public void doBusiness(Context mContext) {
        networkRequest = new NetworkRequest(mContext, this);
        tv_tab_left.performClick();

    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.tv_right:
                showQrPrice();
                break;
            case R.id.tv_tab_left:
                selected();
                tv_tab_left.setSelected(true);
                type = "1";
                refresh();
                break;
            case R.id.tv_tab_right:
                selected();
                tv_tab_right.setSelected(true);
                type = "2";
                refresh();
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(isEntered){
            isEntered=false;
            refresh();
        }
    }

    //重置所有文本的选中状态
    public void selected() {
        tv_tab_left.setSelected(false);
        tv_tab_right.setSelected(false);
    }

    /**
     * 获取信息
     */
    private void getGoodsListStore(boolean isShow) {
        parmMap = new ArrayMap<>();
        Constant.setCommonParams(parmMap, Constant.App.Goods, Constant.classes.GetGoodsListStore);
        parmMap.put("storehouse_id", AppInfo.getUser(getActivity()).getStorehouse_id());//服务站用户id
        parmMap.put("type", type);
        parmMap.put("page", pageNo + "");
        parmMap.put("key", "");
        networkRequest.postJsonRequest(Constant.serverPath, parmMap, Constant.Actionid.NETWORK_REQUEST_CODE_1, isShow, Constant.classes.GetGoodsListStore);
    }

    @Override
    public void onFaild(int orderCode, String result) {
        ToastUtil.showShort(getActivity(), result);
        pullToRefreshLayout.finishLoadMore();
        pullToRefreshLayout.finishRefresh();
    }

    @Override
    public void onSucceed(int orderCode, String result) throws JSONException {
        pullToRefreshLayout.finishLoadMore();
        pullToRefreshLayout.finishRefresh();
        Logger.getLogger(result);
        if (orderCode == Constant.Actionid.NETWORK_REQUEST_CODE_1) {
            GoodsListResponse goodsListResponse = GsonUtil.GsonToBean(result, GoodsListResponse.class);
            if (null != goodsListResponse) {

                if (0 == goodsListResponse.getStatus()) {
                    List<GoodsListModel> mList = goodsListResponse.getData().getGoods_info();


                    if (null != mList && mList.size() > 0) {
                        if (freshState == REFRESHING) {
                            list.clear();
                        }
                        list.addAll(mList);
                        listAdapter.setType(type);
                        listAdapter.setDataList(list);
                        try {
                            totalpage = Integer.parseInt(goodsListResponse.getData().getCount());
                        } catch (NumberFormatException e) {
//                            Log.v(TAG, "返回的总条数不是数字");
                            e.printStackTrace();
                        }
                    } else {
                        if (freshState == REFRESHING) {
                            list.clear();
                            listAdapter.setType(type);
                            listAdapter.setDataList(null);
                            if (pageNo == 1) {
                                ToastUtil.showShort(getActivity(), "暂无数据");
                            }
                        }

                    }

                }


            }


        }
    }

    @Override
    public void refresh() {
        freshState = REFRESHING;
        pageNo = 1;
        getGoodsListStore(false);
    }

    @Override
    public void loadMore() {

        if (pageNo * list.size() < totalpage) {
            freshState = LOADMORE;
            pageNo++;
            getGoodsListStore(false);
        } else {
            pullToRefreshLayout.finishLoadMore();
            ToastUtil.showShort(getActivity(), "没有更多数据了");
        }

    }

    /**
     * 输入金额提示
     */
    protected void showQrPrice() {
        final Dialog dialog = new Dialog(getActivity(), R.style.Dialog_image);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_input_price);
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        final EditText edt = (EditText) dialog.findViewById(R.id.edt_price);
        TextView tv_title = (TextView) dialog.findViewById(R.id.tv_title);
        Button btn_qx = (Button) dialog.findViewById(R.id.btn_one);
        Button btn_qd = (Button) dialog.findViewById(R.id.btn_two);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        if (!dialog.isShowing()) {
            dialog.show();
        }
        edt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        edt.setText(s);
                        edt.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    edt.setText(s);
                    edt.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        edt.setText(s.subSequence(0, 1));
                        edt.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });
        dialog.getWindow().setAttributes(params);

        btn_qx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();

            }
        });
        btn_qd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!TextUtils.isEmpty(edt.getText().toString()) && edt.getText().toString().length() > 0) {
//                    ToastUtil.showShort(MainActivity.this, "提交成功");
                    if (edt.getText().toString().startsWith(".") || edt.getText().toString().endsWith(".")) {
                        ToastUtil.showShort(getActivity(), "请输入正确的金额");
                        return;
                    }
                    dialog.dismiss();
                    isEntered=true;
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                    String price = decimalFormat.format(Double.parseDouble(edt.getText().toString()));//format 返回的是字符串
                    Intent m = new Intent(getActivity(), QrPicActivity.class);
                    m.putExtra("price", price);
                    startActivity(m);
                } else {
                    ToastUtil.showShort(getActivity(), "请输入金额");
                }
            }
        });

    }
}
